package com.example.shushiyunsst.fragment.main.home.child.new_sale

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.example.library_common.adapter.multi.JssNewMultipleAdapter
import com.example.library_common.base.LazyFragment
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.PixUtils
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.recycler.bean.*
import com.example.shushiyunsst.fragment.main.home.child.new_sale.recycler.provider.*
import com.example.shushiyunsst.util.*
import com.example.wallet.db.UserInfoManager
import kotlin.math.abs

/**
 * 新零售
 * */
@Route(path = NEW_SALE)
class NewSaleFragment : LazyFragment(), SwipeRefreshLayout.OnRefreshListener {

    companion object {
        fun newInstance(): NewSaleFragment {
            val args = Bundle()

            val fragment = NewSaleFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun getLayoutId() = R.layout.new_sale_fragment

    private lateinit var mSwipeRefreshLayout: SwipeRefreshLayout

    private lateinit var mRecyclerView: RecyclerView

    private lateinit var mAdapter: JssNewMultipleAdapter<NewSaleEntity>

    private var mData = mutableListOf<NewSaleEntity>()

    private var mDistance = 0

    private lateinit var mNewSaleHeaderLayout: View

    private lateinit var mHeaderViewBg: View

    private val modMap = mapOf(
        "topList" to NewSaleBannerWrapperEntity::class.java,
        "shopNewsList" to NewSaleNotifyWrapperEntity::class.java,
        "shopMessageList" to NewSaleMineWrapperEntity::class.java,
        "midleList" to NewSaleAdvertiseWrapperEntity::class.java,
        "downList" to NewSaleCurrencyWrapperEntity::class.java
    )

    override fun initView(view: View) {

        view.findViewById<View>(R.id.mPageBack).setOnClickListener { onBackPressedSupport() }

        mHeaderViewBg = view.findViewById(R.id.mHeaderViewBg)

        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.new_sale)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mNewSaleHeaderLayout = view.findViewById(R.id.mNewSaleHeaderLayout)

        view.findViewById<View>(R.id.headerLayout).setBackgroundColor(Color.TRANSPARENT)

        mSwipeRefreshLayout = view.findViewById(R.id.mSwipeRefreshLayout)

        mSwipeRefreshLayout.setColorScheme(R.color.nav_bar_bg_color)

        mSwipeRefreshLayout.setProgressBackgroundColor(R.color.colorAccent)

        mRecyclerView = view.findViewById(R.id.mRecyclerView)

        mRecyclerView.setHasFixedSize(true)

        mRecyclerView.layoutManager =
            LinearLayoutManager(_mActivity, LinearLayoutManager.VERTICAL, false)

        mAdapter = JssNewMultipleAdapter<NewSaleEntity>(mData)

        registerBeanWithProvider()

        mRecyclerView.adapter = mAdapter

        mAdapter.lifecycle = lifecycle

        mAdapter.lifecycleOwner = this

        mAdapter.setAdapterViewItemViewClick { m, viewType ->

            when (viewType) {
                NewSaleEntity.NEW_SALE_CURRENCY_TYPE -> {
                    if (m !is NewSaleCurrencyEntity) {
                        return@setAdapterViewItemViewClick
                    }

                    ARouter.getInstance()
                        .build(GOODS_DETAIL)
                        .withString(GOODS_ID, m.goodsId.toString())
                        .startNavigation(this)

                }
                NewSaleEntity.NEW_SALE_FUN_TYPE -> {
                    if (m !is NewSaleFunEntity) {
                        return@setAdapterViewItemViewClick
                    }
                    if(m.routerPath.isNotEmpty()){
                        ARouter.getInstance()
                            .build(m.routerPath)
                            .startNavigation(this)
                    }

                }
            }

        }
        mSwipeRefreshLayout.setProgressViewOffset(false, 0, PixUtils.dp2px(60))

        mSwipeRefreshLayout.setOnRefreshListener(this)

//        mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                super.onScrolled(recyclerView, dx, dy)
//
//                val height = mRecyclerView.paddingTop
//
//                mDistance += dy
//
//                var alpha = abs(mDistance) * 1.0f / (height * 1.0f)
//                alpha = if (alpha >= 1.0f) 1.0f else alpha
//
//                mHeaderViewBg.alpha = alpha
//
//            }
//        })

    }

    override fun lazyInit() {

        mSwipeRefreshLayout.isRefreshing = true

        onRefresh()
    }

    private fun registerBeanWithProvider() {
        mAdapter.register(
            NewSaleAdvertiseWrapperEntity::class.java,
            NewSaleAdvertiseProvider::class.java
        )

        mAdapter.register(
            NewSaleBannerWrapperEntity::class.java,
            NewSaleBannerProvider::class.java
        )

        mAdapter.register(
            NewSaleCurrencyWrapperEntity::class.java,
            NewSaleCurrencyProvider::class.java
        )

        mAdapter.register(
            NewSaleFunWrapperEntity::class.java,
            NewSaleFunProvider::class.java
        )

        mAdapter.register(
            NewSaleMineWrapperEntity::class.java,
            NewSaleMineProvider::class.java
        )

        mAdapter.register(
            NewSaleNotifyWrapperEntity::class.java,
            NewSaleNotifyProvider::class.java
        )
    }


    private fun endTrans() {

        val mWrapper = NewSaleFunWrapperEntity()

        mWrapper.addData(getNewSaleFunList())

        if (mAdapter.itemCount > 2) {
            mData.add(2, mWrapper)
//            mAdapter.addData(2, mWrapper)
        } else {
            mData.add(mWrapper)
//            mAdapter.addData(mWrapper)
        }

    }

    private fun loadData() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid,
            "sysWalletAddress" to userInfo?.sysWalletAddress
        )
        RestClient.builder()
            .url(R.string.shopIndex)
            .raw(JSON.toJSONString(maps))
            .success {
                parserData(it)
                endTrans()
                endRefresh()
            }.failure {

                endTrans()

                endRefresh()
            }.error { code, msg ->

                endTrans()

                endRefresh()
            }
            .build()
            .post()
    }

    private fun endRefresh() {

        mAdapter.notifyDataSetChanged()

        if (mSwipeRefreshLayout.isRefreshing) {

            mSwipeRefreshLayout.isRefreshing = false
        }
    }

    private fun parserData(it: String?) {

        val parse = JSON.parseObject(it)

        for (e in modMap.entries) {

            val json = parse[e.key]

            val dataTypeValue = e.value

            var clazz = hookGenericSuperClass(dataTypeValue)

            clazz = (clazz ?: dataTypeValue) as Class<*>

            val entityWrapper = dataTypeValue.newInstance()
                    as NewSaleEntityWrapper<*>

            if (json is JSONArray) {
                val array = JSON.parseArray(

                    json.toJSONString(),

                    clazz
                ) as MutableList<NewSaleEntity>
                if(array.isNotEmpty()){
                    entityWrapper.addData(array)
                    mData.add(entityWrapper)
                }

//                mAdapter.addData(entityWrapper)

            } else if (json is JSONObject) {
                val obj = JSON.parseObject(
                    json.toJSONString(),
                    clazz
                ) as NewSaleEntity
                mData.add(obj)
//                mAdapter.addData(obj)
            }
        }

    }

    override fun onRefresh() {

        mAdapter.clears()

        mSwipeRefreshLayout.postDelayed({ loadData() }, 1000)
    }


    override fun onDestroy() {
        super.onDestroy()
        mAdapter.clears()
    }

}